import React, {Component} from 'react';
import {StyleSheet, Text, View,ActivityIndicator,ScrollView } from 'react-native';
import { Button,ListItem,Divider,Image } from 'react-native-elements';
import Ionicons from 'react-native-vector-icons/Ionicons';
import Api from './Api';
import Storage from './Storage';


export default class NovelDetail extends React.Component {
    static navigationOptions = ({ navigation }) => {
        return {
          title: navigation.getParam('title', '目录'),
          headerBackTitle:'返回',
          headerRight: (
            <Button
              onPress = {() => navigation.navigate('Home')}
              icon={
                <Ionicons
                name="ios-home"
                size={25}
                color="#2089dc"
              />
              }
              type='clear'
            />
            ),
        };
      };
  
    state = { data:[],loaded:false,url:'',showPages:false,novle:{},cacheNovel:false}
    
    showPagesLists = () => {
        this.setState(previousState => {
            return { showPages: !previousState.showPages };
          })
    }

    updateNovel = (mergeNovel) => {
      Storage.getData(mergeNovel.href).then(res=>{
        if(res!==null){
          Storage.mergeData(mergeNovel.href,JSON.stringify(mergeNovel))
        }else{
          Storage.setData(mergeNovel.href,JSON.stringify(mergeNovel))
        }
      })
    }

    componentDidMount(){
        const { navigation } = this.props;
        let url = navigation.getParam('url', '');
        let tmpNovel=null;
        Storage.getData(url).then(res=>{
          if(res!==null){
            tmpNovel=JSON.parse(res);
            this.setState({cacheNovel:tmpNovel})
          }
        })

        this.setState({url:url})

        Api.detailNovel({url:url})
            .then((res) => {
                let novel={
                  cover:res.detail.cover,
                  title:res.detail.title,
                  href:url,
                  pageHref:tmpNovel!==null?tmpNovel.pageHref:url,
                  reading:tmpNovel!==null?tmpNovel.reading:res.detail.updated_title,
                  url:tmpNovel!==null?tmpNovel.url:res.detail.updated_url
                }
                this.setState({
                  novel:novel,
                  data:res,
                  loaded:true
                })
                if(tmpNovel===null){
                  this.updateNovel(novel)
                }
            })
  
    }

    changePage=(url)=>{
        let novel=this.state.novel;
        novel=Object.assign(novel,{pageHref:url});
        this.setState({showPages:false,novel:novel,loaded:false})
        Api.detailNovel({url:url})
            .then((res) => {
                this.setState({
                    data:res,
                    loaded:true
                })
            })
    }

    render() {
        let {loaded,data,url,showPages,cacheNovel} = this.state
        return (
          <View style={{ flex: 1,padding:10,}}>
            {loaded ?
                <>
                    <View style={{height:140}}>
                        <View style={styles.container}>
                            <Image source={{uri:data.detail.cover}} style={{ width: 100,height:130 }} PlaceholderContent={<ActivityIndicator />} />
                            <View style={{ flex: 1,paddingLeft:10,}}>
            
                                <Text style={styles.title}>{data.detail.type} {data.detail.author}</Text>
                                 
                                <Text style={styles.title}>{data.detail.status} {data.detail.updated_at}</Text>
                                
                                {cacheNovel?
                                  <Button type="clear" onPress={() => this.props.navigation.navigate('Article',{
                                    url:cacheNovel.url,
                                    href:url,
                                    title:cacheNovel.reading,
                                    scroll:1
                                })} titleStyle={{color:"#333",fontSize:16}} title={cacheNovel.reading}/>
                                :
                                <Button type="clear" onPress={() => this.props.navigation.navigate('Article',{
                                  url:data.detail.updated_url,
                                  href:url,
                                  title:data.detail.updated_title
                              })} titleStyle={{color:"#333",fontSize:16}} title={data.detail.updated_title}/>
                                }
                            </View>
                        </View> 
                        <Divider style={{ backgroundColor: '#EEE' }} />
                    </View>
                    <View style={{flex:1}}>
                        {showPages?
                                <ScrollView>
                                  {
                                    data.page.map((l, i) => (
                                    <ListItem
                                        key={`${i}`}
                                        onPress={() => this.changePage(l.href)}
                                        title={l.title}
                                        containerStyle={{
                                          backgroundColor:i%2===0?'#FFF':'#F7F7F7'
                                      }}
                                        rightIcon={
                                            <Ionicons
                                                name="ios-arrow-forward"
                                                size={15}
                                                color="#2089dc"
                                                />
                                        }
                                    />
                                    ))
                                }
                                </ScrollView>
                                :
                                <ScrollView>
                                  {
                                    data.directory.map((l, i) => (
                                    <ListItem
                                        key={i}
                                        onPress={() => this.props.navigation.navigate('Article',{
                                            url:l.href,
                                            href:url,
                                            title:l.title
                                        })}
                                        title={l.title}
                                        containerStyle={{
                                          backgroundColor:i%2===0?'#FFF':'#F7F7F7'
                                      }}
                                        rightIcon={
                                            <Ionicons
                                                name="ios-arrow-forward"
                                                size={15}
                                                color="#2089dc"
                                                />
                                        }
                                    />
                                    ))
                                }
                                </ScrollView>
                        }
                    </View>
                    <View style={{height:40}}>
                        {showPages?
                            <Button title="隐藏页码" onPress={this.showPagesLists}/>
                            :
                            <Button title="显示页码" onPress={this.showPagesLists}/>
                        }
                    </View>
                </>
                :
                <View style={styles.horizontal}>
                    <ActivityIndicator size="small" color="#00ff00" />
                    <Text>Loading...</Text>
                </View>
            }
          </View>
        );
    }
  }

  const styles = StyleSheet.create({
    container: {
      flex: 1,
      flexDirection: "row",
      justifyContent: "center",
      alignItems: "center",
      paddingLeft:5,
      paddingRight:5,
    },
    horizontal: {
      flex: 1,
      justifyContent: 'center',
      alignItems: "center",
      flexDirection: 'column',
      padding: 10
    },
    rightContainer: {
      flex: 1,
      alignItems:"center",
      paddingLeft: 10,
    },
    title: {
      fontSize: 16,
      marginBottom: 5
    },
    year: {
      textAlign: "center"
    },
    thumbnail: {
      width: 53,
      height: 81
    },
    list: {
      paddingTop: 20
    }
  });